<template>
  <van-field
    v-if="h5"
    class="m-van-cell"
    :name="item.options && item.options.name"
    :label="item.options && item.options.label"
    :required="item.options && !isDetail && item.options.required"
    :rules="isDetail ? [] : vantRules"
    :border="false"
    :label-width="item.options?.labelPosition === 'top' ? '100%' : undefined"
    :label-align="(item.options && item.options.labelPosition) || undefined"
    :input-align="(item.options && item.options.inputAlign) || undefined"
    :error="false"
  >
    <template #input>
      <slot name="tip">
        <div v-if="item.options.tip" class="van-correlation__tip">
          {{ item.options.tip }}
        </div>
      </slot>
      <transition-group tag="ul" class="correlation-list" name="list">
        <li v-for="(obj, i) in fieldModel" :key="i" class="correlation-item" :tabindex="i">
          <slot :item="obj" :remove="() => fieldModel.splice(i, 1)">
            <span v-show="!designer">请在表单组件中使用correlation插槽</span>
          </slot>
        </li>
      </transition-group>
      <div v-if="!isDetail" class="footer">
        <slot name="btn">
          <van-button plain hairline type="primary" icon="add-o" size="small" @click="popupVisible = true">
            添加审批
          </van-button>
        </slot>
      </div>
    </template>
  </van-field>
  <widget-form-item
    v-else
    :designer="designer"
    :widget-list="widgetList"
    :item="item"
    :rules="isDetail ? [] : rules"
    :index="index"
    :show-message="!isDetail"
  >
    <transition-group tag="ul" class="correlation-list" name="list">
      <li v-for="(obj, i) in fieldModel" :key="i" class="correlation-item" :tabindex="i">
        <slot :item="obj" :remove="() => fieldModel.splice(i, 1)">
          <span v-show="!designer">请在表单组件中使用correlation插槽</span>
        </slot>
      </li>
    </transition-group>
    <div v-if="!isDetail" class="ep-footer">
      <slot name="btn">
        <el-button plain @click="dialogVisible = true">
          <template #icon>
            <Plus />
          </template>
          添加审批
        </el-button>
      </slot>
      <slot name="tip">
        <div v-if="item.options.tip" class="ep-correlation__tip">
          {{ item.options.tip }}
        </div>
      </slot>
    </div>
  </widget-form-item>
  <el-dialog :key="showIndex" v-model="dialogVisible" title="选择关联审批" class="correlation-dialog" append-to-body>
    <slot name="dialog" :options="item.options" :callback="onCallback">
      <span v-show="!designer">请在表单组件中使用correlation-dialog插槽</span>
    </slot>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSave"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
  <van-popup
    :key="showIndex"
    v-model:show="popupVisible"
    position="right"
    :style="{ width: '100%', height: '100%' }"
    safe-area-inset-top
    safe-area-inset-bottom
  >
    <van-nav-bar title="选择审批" left-arrow="" z-index="99" placeholder @click-left="popupVisible = false" />
    <slot name="dialog" :options="item.options" :callback="onCallback" :save="onSave">
      <span v-show="!designer">请在表单组件中使用correlation-dialog插槽</span>
    </slot>
  </van-popup>
</template>

<script>
import { ref, reactive, computed, watch, getCurrentInstance } from 'vue'
import props from './props'
import field from './field'
import { showToast } from 'vant'

export default {
  name: 'MCorrelation',
  props,
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const dialogVisible = ref(false)
    const popupVisible = ref(false)

    const { proxy } = getCurrentInstance()

    let showIndex = 0

    /** 初始化 */
    watch([dialogVisible, popupVisible], (val) => {
      if (val[0] !== val[1]) {
        showIndex++
        list = props.modelValue || []
      }
    })

    let list = props.modelValue || []
    const onCallback = (e) => {
      list = [...e]
    }

    const selectIds = computed(() => {
      return list.map((m) => m.id)
    })

    const onSave = () => {
      const { limit, tip } = props.item.options
      if (list.length > limit) {
        if (props.h5) {
          showToast({
            message: tip || '超出最多关联数量',
            icon: 'info-o',
            iconSize: '20px'
          })
        } else {
          proxy.$message.error(tip || '超出最多关联数量')
        }
        return false
      }
      dialogVisible.value = false
      popupVisible.value = false
      emit('update:modelValue', list)
    }

    const vantRules = [
      {
        validator: () =>
          new Promise((resolve) => {
            resolve(!props.item.options.required || list.length > 0)
          })
      }
    ]

    return {
      ...field(props, emit),
      showIndex,
      list,
      selectIds,
      dialogVisible,
      popupVisible,
      vantRules,
      onCallback,
      onSave
    }
  }
}
</script>

<style lang="scss" scoped>
.m-van-cell {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.correlation-list {
  display: flex;
  flex-direction: column;
  width: 100%;
}
.ep-footer {
  display: flex;
  flex-direction: column;
  padding-top: 5px;
}
.footer {
  display: flex;
  flex-direction: column;
  padding-top: 10px;
  width: 100%;
  align-items: center;
}
.ep-correlation__tip {
  font-size: 12px;
  color: var(--el-color-info);
  margin-top: 7px;
}
.van-correlation__tip {
  color: var(--el-color-info);
  margin-top: 7px;
}
:deep .van-field__control--custom {
  flex-direction: column;
  align-items: flex-start;
}
:deep .van-cell__value {
  width: 100%;
}
</style>
